package com.gxuwz.weather.adapter;
import androidx.core.content.ContextCompat;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.gxuwz.weather.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CityDeliteAdpter extends BaseAdapter {

    private Context context;
    private List<Map<String, String>> data;
    private List<Integer> selectedPositions = new ArrayList<>();
    private LayoutInflater inflater;

    public CityDeliteAdpter(Context context, List<Map<String, String>> data) {

        this.context = context;
        this.data = data;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_city_deletecity, parent, false);
            holder = new ViewHolder();
            holder.tvDeleteAreaName = convertView.findViewById(R.id.tv_delete_area_name);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Map<String, String> cityInfo = data.get(position);
        holder.tvDeleteAreaName.setText(cityInfo.get("areaCn"));
        // 设置选中状态
        if (selectedPositions.contains(position)) {
            convertView.setBackgroundColor(ContextCompat.getColor(context, R.color.gray));
        } else {
            convertView.setBackgroundColor(ContextCompat.getColor(context, R.color.white));
        }

        return convertView;
    }

    private static class ViewHolder {
        TextView tvDeleteAreaName;
    }

    public void toggleSelection(int position) {
        if (selectedPositions.contains(position)) {
            selectedPositions.remove(Integer.valueOf(position));
        } else {
            selectedPositions.add(position);
        }
        notifyDataSetChanged();
    }

    public List<Map<String, String>> getSelectedItems() {
        List<Map<String, String>> selectedItems = new ArrayList<>();
        for (Integer position : selectedPositions) {
            selectedItems.add(data.get(position));
        }
        return selectedItems;
    }

    public void updateData(List<Map<String, String>> newData) {
        this.data = newData;
        selectedPositions.clear();
        notifyDataSetChanged();
    }
}
